<template>
  <div id="app">
	<Layout ref="layout" />
	<Login v-model="to_login" :tencentCaptchaId="tencentCaptchaId" />
  </div>
</template>

<script>
import Layout from './components/Layout.vue'
import Login from './components/pages/Login.vue'
import config from './global_config.js'

export default {
	name: 'app',
	data() {
		return {
			tencentCaptchaId: config.tencentCaptchaId,
			to_login: false,
			access_token: null
		}
	},
	methods: {
		openLoginPage() {
			this.to_login = true
		},
		closeLoginPage() {
			this.to_login = false
		},
		refreshToken(newToken) {
			localStorage.setItem("access_token", newToken)
		},
		removeToken(){
			localStorage.removeItem("access_token")
		},
		getToken() {
			return localStorage.getItem("access_token")
		},
		reloadView() {
			this.$refs.layout.reload_view()
		}
	},
	mounted() {
		this.$axios.interceptors.request.use(
			res => {
				// 对每个请求自动绑定 backend 和 access_token
				if(!res.resend) res.url = config.backend + res.url
				res.timeout = 15000
				if(localStorage.getItem('access_token') != null)
					res.headers.access_token =  localStorage.getItem('access_token')
				
				return res
			}
		);
		this.$axios.interceptors.response.use(
			resp => {
				if(resp.status == 200) {
					switch(resp.data.ret) {
						case 1000:
							// access_token 已刷新，需要拿到服务器返回的最新的 access_token 进行请求重发
							this.refreshToken(resp.data.data.access_token)
							resp.headers.access_token = this.getToken()
							
							resp.config.resend = true
							return this.$axios.request(resp.config)
							
						case 1001:
							// access_token 已过期，需要重新登录
							// this.$msg("无效的会话凭证")
							// this.openLoginPage()
							return resp.data
							
						case -1:
							// 通用错误状态码
							if(resp.data.msg != null){
								this.$msg(resp.data.msg == "failure" && resp.data.data != null ? resp.data.data[0] : resp.data.msg)
								
							} else this.$msg("未知错误")
						default:
							return resp.data
					}
				} else this.$msg("服务器发生错误")
				
				return false
			}
		);
	},
	provide() {
		return {
			to_login: this.openLoginPage,
			close_login: this.closeLoginPage,
			refresh_token: this.refreshToken,
			remove_token: this.removeToken,
			get_token: this.getToken,
			reload_view: this.reloadView,
			access_token: this.access_token
		}
	},
	components: {
		Layout,
		Login
	}
}
</script>

<style>
	html, body {
		height: 100%;
	}
	body {
		margin: 0;
		padding: 0;
	}
	.clear {
		clear: both;
	}
</style>
